package com.ceolt.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**************
 * 从标准输入流获取数据的工具类
 * @author yejf
 *
 */
public class InputUtil {

	/** 字符输入流 */
	private static BufferedReader in;
	
	/******
	 * 静态代码块，来构建BufferedReader
	 */
	static {
		in = new BufferedReader(new InputStreamReader(System.in));
	}
	
	/*****************
	 * 输入一个整数
	 * @param msg
	 * @return
	 */
	public static int inputInt(String msg, Object... args) {
		int result= -1;
		System.out.printf(msg,args);
		try {
			String line = in.readLine();
			//
			if(line != null && line.trim().length() > 0) {
				result = Integer.parseInt(line.trim());
			} else {
				System.out.println("警告：请不要输入空白字符");
				return inputInt(msg,args);
			}
		} catch (Exception e) {
			//处理异常
			System.out.println("警告：输入不是的整数");
			return inputInt(msg,args);
		}
		return result;
	}
	
	/*******************
	 * 输入一个字符
	 * @param msg
	 * @return
	 */
	public static char inputLetter(String msg, Object... args) {
		char result = '\u0000';
		System.out.printf(msg,args);
		try {
			String line = in.readLine();
			//
			if(line != null && line.trim().length() > 0) {
				result = line.trim().charAt(0);
				//进一步判断
				if(!Character.isLetter(result)) {
					System.out.println("警告：输入的不是字母");
					return inputLetter(msg, args);
				}
			} else {
				System.out.println("警告：请不要输入空白字符");
				return inputLetter(msg, args);
			}
		} catch (Exception e) {
			//处理异常
			System.out.println("输入有误");
			return inputLetter(msg, args);
		}
		//
		return result;
	}
	
	/***************
	 * 输入字符串
	 * @param msg
	 * @return
	 */
	public static String inputString(String msg, Object... args) {
		String result = null;
		System.out.printf(msg, args);
		try {
			result = in.readLine();
			//
			if(result != null && result.trim().length() > 0) {
				return result.trim();
			} else {
				System.out.println("警告：请不要输入空白字符");
				return inputString(msg, args);
			}
		} catch (Exception e) {
			//处理异常
			System.out.println("输入有误");
			return inputString(msg, args);
		}
	}
	
	public static void main(String[] args) {
		int i = inputInt("请输入一个整数[%d,%d]>",1,5);
		System.out.println(i);
	}
}
